package cn.signalpha.modules.social.controller.api;

import cn.signalpha.common.annotation.FormRepeatCommitAnnotation;
import cn.signalpha.common.constant.AppConstant;
import cn.signalpha.common.constant.MsgConstant;
import cn.signalpha.common.dto.IdDTO;
import cn.signalpha.common.utils.Assert;
import cn.signalpha.core.boot.ctrl.BaseController;
import cn.signalpha.core.mp.support.Condition;
import cn.signalpha.core.mp.support.Query;
import cn.signalpha.core.tool.api.R;
import cn.signalpha.core.tool.jackson.JsonUtil;
import cn.signalpha.core.tool.support.Kv;
import cn.signalpha.core.tool.utils.CollectionUtil;
import cn.signalpha.core.tool.utils.Func;
import cn.signalpha.modules.shop.entity.OrderDetail;
import cn.signalpha.modules.shop.service.OrderDetailService;
import cn.signalpha.modules.shop.vo.OrderGoodsVO;
import cn.signalpha.modules.social.dto.TopicDTO;
import cn.signalpha.modules.social.entity.Topic;
import cn.signalpha.modules.social.service.BlacklistService;
import cn.signalpha.modules.social.service.FansService;
import cn.signalpha.modules.social.service.TopicService;
import cn.signalpha.modules.social.vo.TopicVO;
import cn.signalpha.modules.social.wrapper.TopicWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.*;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.validation.Valid;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 控制器
 *
 * @author signalpha
 */
@RestController
@AllArgsConstructor
@RequestMapping(AppConstant.APPLICATION_SOCIAL_NAME + "/wap/topic")
@Api(value = "论坛主题", tags = "论坛主题")
public class ApiTopicController extends BaseController {

	private final FansService fansService;
	private final TopicService topicService;
	private final BlacklistService blacklistService;
	private final OrderDetailService orderDetailService;

    @GetMapping("/focus/page")
	@ApiOperationSupport(order = 1)
    @ApiOperation(value = "关注列表", notes = "")
    public R<IPage<TopicVO>> focusPage(Query query) {
		List<Long> userIds  = fansService.getUserIds(getUser().getUserId());
		if(CollectionUtil.isEmpty(userIds)){
			return R.data(new Page<>());
		}
		Map<String, Object> params = Kv.create().set("userIds", userIds).set("isShow", "1").set("status","1");
		IPage<TopicVO> page = topicService.selectTopicPage(Condition.getPage(query), params);
        return R.data(TopicWrapper.build().page(page, getUser().getUserId()));
    }

	@GetMapping("/push/page")
	@ApiImplicitParams({
		@ApiImplicitParam(name="tag", dataType = "string", value = "标签"),
		@ApiImplicitParam(name="title", dataType = "string", value = "标题"),
		@ApiImplicitParam(name="categoryId", dataType = "string", value = "分类id"),
	})
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "推荐列表", notes = "")
	public R<IPage<TopicVO>> pushPage(@ApiIgnore @RequestParam Map<String, Object> params, Query query) {
		query.setDescs("like_num");
		params.put("isShow", "1");
		params.put("status", "1");

		//黑名单
//		List<Long> userIds  = blacklistService.getUserIds(getUser().getUserId());
//		if(CollectionUtil.isNotEmpty(userIds)){
//			params.put("userNotIds", userIds);
//		}
		IPage<TopicVO> page = topicService.selectTopicPage(Condition.getPage(query), params);
		List<Long> ids = Func.toLongList(String.valueOf(params.get("ids")));
		if(CollectionUtil.isNotEmpty(ids)){
			page.getRecords().sort(((o1, o2) -> {
				int io1 = ids.indexOf(o1.getId());
				int io2 = ids.indexOf(o2.getId());
				if (io1 != -1) {
					io1 = page.getRecords().size() - io1;
				}
				if (io2 != -1) {
					io2 = page.getRecords().size() - io2;
				}
				return io2 - io1;
			}));
		}
		return R.data(TopicWrapper.build().page(page, getUser().getUserId()));
	}

	@GetMapping("/target/page")
	@ApiImplicitParams({
		@ApiImplicitParam(name="targetId", dataType = "string", value = "活动id"),
	})
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "活动关联列表", notes = "")
	public R<IPage<TopicVO>> targetPage(@ApiIgnore @RequestParam Map<String, Object> params, Query query) {
		params.put("isShow", "1");
		params.put("status", "1");
		Assert.isNull(params.get("targetId"), "targetId不能为空");
		IPage<TopicVO> page = topicService.selectTopicPage(Condition.getPage(query), params);
		return R.data(TopicWrapper.build().page(page, getUser().getUserId()));
	}

	@GetMapping("/info")
	@ApiOperationSupport(order = 5)
	@ApiOperation(value = "详情", notes = "传入id")
	public R<TopicVO> info(@ApiParam(value = "主键", required = true) @RequestParam Long id) {
		return R.data(TopicWrapper.build().entityVO(topicService.getById(id), getUser().getUserId()));
	}

	@GetMapping("/detail")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "详情 不鉴权", notes = "传入id")
	public R<Topic> detail(@ApiParam(value = "主键", required = true) @RequestParam Long id) {
		return R.data(TopicWrapper.build().entityVO(topicService.getById(id)));
	}

	@PostMapping("/save")
	@FormRepeatCommitAnnotation
	@ApiOperationSupport(order = 7)
	@ApiOperation(value = "发布主题", notes = "")
	public R save(@Valid @RequestBody TopicDTO.SaveDTO topicDTO) {
		topicDTO.setUserId(getUser().getUserId());
		return R.status(topicService.saveTopic(topicDTO));
	}

	@PostMapping("/update")
	@ApiOperationSupport(order = 8)
	@ApiOperation(value = "编辑主题", notes = "")
	public R remove(@Valid @RequestBody TopicDTO.UpdateDTO topicDTO) {
		Topic data = topicService.getById(topicDTO.getId());
		Assert.isNull(data, MsgConstant.OBJECT_NULL);
		Assert.isTrue(getUser().getUserId().equals(data.getUserId()), MsgConstant.UNAUTHORIZED);
		return R.status(topicService.updateTopic(topicDTO));
	}

	@GetMapping("/user/goods/list")
	@ApiOperationSupport(order = 10)
	@ApiOperation(value = "添加关联列表", notes = "")
	public R<List<OrderGoodsVO>> orderPage() {
		Long userId = getUser().getUserId();
		List<OrderGoodsVO> goodsList = new ArrayList<>();
		orderDetailService.list(Wrappers.<OrderDetail>lambdaQuery().eq(OrderDetail::getUserId, userId)).forEach(orderDetail -> {
			goodsList.add(JsonUtil.parse(orderDetail.getGoodsDetail(), OrderGoodsVO.class));
		});
		return R.data(goodsList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparingLong(OrderGoodsVO::getId))), ArrayList::new)));
	}

	@PostMapping("/remove")
	@ApiOperationSupport(order = 20)
	@ApiOperation(value = "删除主题", notes = "传入id")
	public R remove(@Valid @RequestBody IdDTO idDTO) {
		Topic topic = topicService.getById(idDTO.getId());
		Assert.isNull(topic, MsgConstant.OBJECT_NULL);
		Assert.isTrue(topic.getUserId().equals(getUser().getUserId()), MsgConstant.UNAUTHORIZED);
		return R.status(topicService.removeById(idDTO.getId()));
	}

}
